package com.yylany.controller;

import com.yylany.bo.CategoryResult;
import com.yylany.enums.ResultEnum;
import com.yylany.pojo.TbCategory;
import com.yylany.service.CategoryService;
import com.yylany.vo.CategoryResults;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * Description: pinyougou
 *
 * @author <a href="mailto:17777502615@163.com">yaoyonglong</a>
 * @date 2018/12/19
 * @since 1.0.0
 */
@RestController
@RequestMapping
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取推荐的商品
     *
     * @return 返回菜单
     */
    @GetMapping("/categorys")
    public ResponseEntity<Object> findAllCategory() {

        // 1 创建返回结果data
        List<CategoryResult> crList0 = new ArrayList<>();

        // 2 调用service层,返回的是一级菜单
        List<TbCategory> categorys0 = categoryService.findCategorys(0, 0);
        // 遍历一级菜单，查询所有的二级菜单
        categorys0.forEach(cat0 -> {
            // 将一级的结果赋值给CategoryResult
            CategoryResult cr0 = new CategoryResult();
            // 拷贝属性
            BeanUtils.copyProperties(cat0, cr0);

            //  创建二级分类集合
            List<CategoryResult> crList1 = new ArrayList<>();

            //  查找二级分类
            List<TbCategory> categorys1 = categoryService.findCategorys(cr0.getId(), 0);
            // 遍历二级菜单，查询所有的三级菜单
            categorys1.forEach(cat1 -> {
                // 将二级分类的结果赋值给CategoryResult
                CategoryResult cr1 = new CategoryResult();
                BeanUtils.copyProperties(cat1, cr1);

                // 4.3.1 创建三级分类集合
                List<CategoryResult> crList2 = new ArrayList<>();
                //  4.3.1 查找三级分类
                List<TbCategory> categorys2 = categoryService.findCategorys(cr0.getId(), cr1.getId());
                categorys2.forEach(cat2 -> {
                    // 4.3.3 将三级分类的结果赋值给CategoryResult
                    CategoryResult cr2 = new CategoryResult();
                    BeanUtils.copyProperties(cat2, cr2);
                    crList2.add(cr2);
                });

                // 将crList2 给cr1
                cr1.setChildren(crList2);
                crList1.add(cr1);
            });
            // 4.2.3 将crList1给cr0
            cr0.setChildren(crList1);

            crList0.add(cr0);
        });

        // 5 组装返回结果BaseResult
        CategoryResults br = new CategoryResults(ResultEnum.CATEGORY_SUCCESS.getErrno(), ResultEnum.CATEGORY_SUCCESS.getErrmsg(), crList0);
        // 6 拼接系统需要的data数据
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", br);

        return ResponseEntity.ok(map);
    }

}
